let loadingService = true; //等待层状态
import {
	devDomain,
	prdDomain
} from "@/config/config.js";
// import jsencrypt from "../js_sdk/jsencrypt-Rsa/jsencrypt/jsencrypt.vue";
import CryptoJS from "crypto-js";
import moment from 'moment';
import Intl from 'intl';
moment.defineLocale('zh-cn', {
	relativeTime: {
		future: '%s内',
		past: '%s前',
		s: '几秒',
		m: '1分钟',
		mm: '%d分钟',
		h: '1小时',
		hh: '%d小时',
		d: '1天',
		dd: '%d天',
		M: '1个月',
		MM: '%d个月',
		y: '1年',
		yy: '%d年'
	},
});
// import {
// 	logout,
// 	getToken
// } from './auth.js';
// import store from "../store/index.js"


import {
	checkIDCard_province,
	checkIDCard_birthday,
	checkParity
} from './IDCardVerification.js';



const api = {

	/**
	 * 成功提示
	 */
	success: (msg) => {

		return new Promise((relove, reject) => {
			uni.showToast({
				title: msg,
				icon: "success"
			})
			setTimeout(() => {
				relove();
			}, 1500)
		})
	},

	/**
	 * 失败提示
	 */
	error: (msg) => {

		return new Promise((relove, reject) => {

			uni.showToast({
				title: msg,
				icon: "none",
				duration: 2500
			})
			setTimeout(() => {
				relove();
			}, 2500)
		})

	},

	/**
	 * 等待层
	 */
	showWaiting: () => {

		loadingService = true;

		setTimeout(() => {

			if (loadingService) {
				uni.showLoading({
					title: '加载中',
					mask: true
				});

			}

		}, 200)

	},

	/**
	 * 关闭等待层
	 */
	closeWaiting: () => {

		loadingService = false;
		uni.hideLoading();
	},

	/**
	 * 确认对话框
	 * @param {Object} contents
	 * @param {Object} callback
	 */
	confirm: (contents) => {

		return new Promise((relove, reject) => {

			uni.showModal({
				title: '提示',
				content: contents,
				success: function(res) {
					if (res.confirm) {
						relove();
					}
				}
			});

		})

	},

	/**
	 * 获取当前域名
	 */
	getDomain() {
		// store.state.moduleAuth.envJudge  1
		let url = process.env.NODE_ENV === 'development' ? devDomain : prdDomain;
		// let url = prdDomain;
		// if (store?.state?.moduleAuth?.envJudge === 1) {
		// 	url = devDomain
		// } else {
		// 	url = prdDomain
		// }
		return url;

	},
	/**
	 * 跳转
	 * @param {Object} url
	 * @param {Object} params
	 */
	toUrl(url, params = null) {
		if (params) {
			let paramsArr = [];
			Object.keys(params).forEach(key => {
				paramsArr.push(`${key}=${params[key]}`);
			})
			url += "?" + paramsArr.join("&");
		}

		uni.navigateTo({
			url: url
		})
	},
	getSwiperHeight(id, that) {
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				let info = uni.createSelectorQuery().in(that);

				let res = info.select(id).boundingClientRect(data => {
					console.log("data", data);
					resolve(data.height + 20);
				}).exec();

			})

		})
	},

	pagerCount:(count, pageSize)=> {
		
		if (typeof(count) == "number") {
			if (count > 0) {
				try {
					var _pagerCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
					var c = _pagerCount.toFixed(0); //小数取整
					_pagerCount = c > _pagerCount ? c - 1 : c; //过滤四舍五入
					return _pagerCount;
		
				} catch (error) {
					return 0;
				}
		
			} else {
				return 0;
			}
		
		} else {
			return 0;
		}
	},


	add0: (m) => {
		return m < 10 ? '0' + m : m
	},
	/**
	 * 时间戳转格式
	 * @param {*} str 
	 */
	format: (shijianchuo) => {
		//shijianchuo是整数，否则要parseInt转换
		var time = new Date(shijianchuo);
		var y = time.getFullYear();
		var m = time.getMonth() + 1;
		var d = time.getDate();
		var h = time.getHours();
		var mm = time.getMinutes();
		var s = time.getSeconds();
		return y + '-' + api.add0(m) + '-' + api.add0(d) + ' ' + api.add0(h) + ':' + api.add0(mm) + ':' + api
			.add0(s);
	},
	/**
	 * 计算两个时间的差
	 * @param {*} str 
	 */
	GetDateDiff: (startTime, endTime, diffType) => {
		//将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式 
		startTime = startTime.replace(/\-/g, "/");
		endTime = endTime.replace(/\-/g, "/");
		//将计算间隔类性字符转换为小写
		diffType = diffType.toLowerCase();
		var sTime = new Date(startTime); //开始时间
		var eTime = new Date(endTime); //结束时间
		//作为除数的数字
		var timeType = 1;
		switch (diffType) {
			case "second":
				timeType = 1000;
				break;
			case "minute":
				timeType = 1000 * 60;
				break;
			case "hour":
				timeType = 1000 * 3600;
				break;
			case "day":
				timeType = 1000 * 3600 * 24;
				break;
			default:
				break;
		}
		console.log("相减时间", (eTime.getTime() - sTime.getTime()) / parseInt(timeType));
		return (eTime.getTime() - sTime.getTime()) / parseInt(timeType);
	},

	GetRequest: (url) => {
		let query = {};
		if (url.indexOf("?") != -1) {
			const str = url.split('?');
			const pairs = str[1].split("&");
			for (let i = 0; i < pairs.length; i++) {
				const pair = pairs[i].split("=");
				query[pair[0]] = pair[1];
			}
		}
		return query; // 返回对象
	},


	isLogin: (url = "", params = {}) => {
		return new Promise((relove, reject) => {
			if (!getToken()) {
				logout();
				reject({});
				return false;
			}

			if (url != '') {
				api.toUrl(url, params);
				return false;
			}

			relove();

		})

	},

	/**
	 * 将一维数组按要求拆分为2维数组
	 */
	sliceArr: (baseArr = [], n = 1) => {

		if (!baseArr || baseArr.length == 0) {

			return [];
		}

		const list = [];

		let len = baseArr.length;
		let lineNum = len % n === 0 ? len / n : Math.floor((len / n) + 1);
		for (let i = 0; i < lineNum; i++) {
			// slice() 方法返回一个从开始到结束（不包括结束）选择的数组的一部分浅拷贝到一个新数组对象。且原始数组不会被修改。
			let temp = baseArr.slice(i * n, i * n + n);
			list.push(temp);
		}

		return list;
	},


	/* 拨打电话 */
	call: (phone) => {
		console.log("uni.getSystemInfoSync().platform", uni.getSystemInfoSync().platform);

		if (uni.getSystemInfoSync().platform == 'android') {

			api.confirm(`您是否要拨打${phone}`).then(() => {
				uni.makePhoneCall({
					phoneNumber: phone,
					complete: (res) => {
						uni.showToast({
							title: `${res}`
						})
					}
				});
			})
		} else if (uni.getSystemInfoSync().platform == 'ios') {

			uni.makePhoneCall({
				phoneNumber: phone
			});
		}
	},


	/* 跳转微信内置地图*/
	openLocationFunc: (lat, lng, name) => {
		window.location.href =
			`https://uri.amap.com/marker?position=${lng},${lat}&name=${name}&coordinate=gaode&callnative=1`
		// uni.openLocation({
		// 	latitude: Number(lat),
		// 	longitude: Number(lng),
		// 	success: function() {
		// 		console.log('success');
		// 	}
		// });
	},

	idCardAnalysis: (cardNum, type) => {
		if (type == 'sex') {
			// 获取性别
			let sex = '';
			if (parseInt(cardNum.substr(16, 1)) % 2 == 1) {
				sex = '男'
			} else {
				sex = '女'
			}
			return sex;
		} else if (type == 'age') {
			// 获取年龄
			let myDate = new Date();

			let month = myDate.getMonth() + 1;

			let day = myDate.getDate();

			let age = myDate.getFullYear() - cardNum.substring(6, 10) - 1;

			if (cardNum.substring(10, 12) < month || (cardNum.substring(10, 12) == month && cardNum.substring(
					12, 14) <= day)) {
				age++;
			}

			return age;
		}

	},

	//手机号敏感处理
	phoneNumShow: (phone) => {
		let mphone = phone.substring(0, 3) + '****' + phone.substring(7);
		return mphone
	},

	//手机号验证
	validatePhone: (str) => {
		const reg = /^1[3456789]\d{9}$/;
		return reg.test(str);
	},

	isPayPasswordFunc: () => {
		console.log("isPayPasswordFunc");
		if (store.state.moduleAuth.userInfo.isPayPassword != 1) {
			console.log("isPayPasswordFunc1");
			uni.showToast({
				title: '请先去设置支付密码',
				icon: 'none',
				mask: true
			})
			setTimeout(() => {
				api.toUrl('/pages/setUpPwd/index');
			}, 1000)
			return false;
		} else {
			console.log("isPayPasswordFunc2");
			return true;
		}
	},


	isAuthFunc: () => {
		console.log("isAuthFunc");
		if (store.state.moduleAuth.userInfo.isAuth != 1) {
			console.log("isAuthFunc1");
			uni.showToast({
				title: '请先去实名认证！',
				icon: 'none',
				mask: true
			})
			setTimeout(() => {
				api.toUrl('/pages/realName/index');
			}, 1000)
			return false;
		} else {
			console.log("isAuthFunc2");
			return true;
		}
	},

	testingLogin: () => {

		let pages = getCurrentPages(); //当前页

		let url = "";
		if (pages[pages.length - 1].$page.fullPath != '/pages/index/index') {
			url = encodeURIComponent(pages[pages.length - 1].$page.fullPath);
		}
		console.log("url", url);
		if (!store.state.moduleAuth.token) {
			// #ifdef H5
			api.toUrl('/pages/login/index', {
				url: url
			});
			return;
		} else {
			return true;
		}
	},

	countDownFun: (time) => {
		//当前时间戳
		let timestamp = new Date().getTime()
		let times = time - timestamp
		let playTime,
			day = 0,
			hour = 0,
			minute = 0,
			second = 0; //时间默认值
		if (times > 0) {
			second = Math.floor(times / 1000); //未来时间距离现在的秒数
			day = Math.floor(second / 86400); //整数部分代表的是天；一天有24*60*60=86400秒 ；
			second = second % 86400; //余数代表剩下的秒数；
			hour = Math.floor(second / 3600); //整数部分代表小时；
			second %= 3600; //余数代表 剩下的秒数；
			minute = Math.floor(second / 60);
			second %= 60;
		}
		//不足两位时添加0
		if (day <= 9) day = '0' + day;
		if (hour <= 9) hour = '0' + hour;
		if (minute <= 9) minute = '0' + minute;
		if (second <= 9) second = '0' + second;

		if (day > 0) {
			playTime = `${day}天${hour}小时${minute}分钟${second}秒`;
		}
		if (day <= 0 && hour > 0) {
			playTime = `${hour}小时${minute}分${second}秒`;
		}
		if (day <= 0 && hour <= 0) {
			playTime = `${minute}分钟${second}秒`;
		}
		return playTime
	},


	checkFormat_IDCardNumber: (idCardNumber) => {
		var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
		if (idCardNumber == "") {
			return false;
		} //校验长度，类型
		else if (reg.test(idCardNumber) === false) {
			console.log("错误1");
			return false;
		} else if (checkIDCard_province(idCardNumber) === false) {
			console.log("错误2");
			//校验省份
			return false;
		} else if (checkIDCard_birthday(idCardNumber) === false) {
			console.log("错误3");
			//校验生日
			return false;
		} else if (checkParity(idCardNumber) === false) {
			console.log("错误4");
			//检验位的检测
			return false;
		}
		return true;
	},


	preview: (imgArr, index) => {
		let arr = [];
		imgArr.map(opt => {
			arr.push(opt)
		})
		console.log("arr", arr);

		// 预览图片
		uni.previewImage({
			urls: arr,
			current: index,
			longPressActions: {
				itemList: ['保存图片'],
				success: function(data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
					uni.downloadFile({
						url: arr[data.index],
						success: (res) => {
							console.log(res)
							if (res.statusCode === 200) {
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: function() {
										uni.showToast({
											title: "保存成功",
											icon: "none"
										});
									},
									fail: function() {
										uni.showToast({
											title: "保存失败",
											icon: "none"
										});
									}
								});
							}
						}
					})
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		});
	},


	hidePartText: (text, start, stop, replacetext) => {
		if (!text) {
			text = "";
		}
		let value = text.substring(0, start - 1) + replacetext + text.substring(stop + 1);
		return value;
	},

	/**
	 * RSA公钥加密
	 * @param {Object} encrypt_key
	 * @param {Object} clearText
	 */
	encryptRsa: (encrypt_key, clearText) => {
		//注意此处上下的BEGIN PRIVATE KEY不要删除，框架自带的
		const public_key = '-----BEGIN PUBLIC KEY-----\n' +
			encrypt_key +
			'\n-----END PUBLIC KEY-----';
		return jsencrypt.setEncrypt(public_key, clearText);
	},

	/**
	 * AES加密
	 * @param {Object} word
	 * @param {Object} keyStr
	 */
	encryptAes: (word, keyStr) => {
		var key = CryptoJS.enc.Utf8.parse(keyStr);
		var srcs = CryptoJS.enc.Utf8.parse(word);
		var encrypted = CryptoJS.AES.encrypt(srcs, key, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
		return encrypted.toString();
	},

	/**
	 * AES解密
	 * @param {Object} word
	 * @param {Object} keyStr
	 */
	decryptAes: (word, keyStr) => {
		var key = CryptoJS.enc.Utf8.parse(keyStr);
		let base64 = CryptoJS.enc.Base64.parse(word);
		let src = CryptoJS.enc.Base64.stringify(base64);
		var decrypt = CryptoJS.AES.decrypt(src, key, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
		return decrypt.toString(CryptoJS.enc.Utf8);
	},


	/**
	 * 随机生成字符串
	 * @param len 指定生成字符串长度
	 */
	getRandomString: (len) => {
		let _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789',
			min = 0,
			max = _charStr.length - 1,
			_str = ''; //定义随机字符串 变量
		//判断是否指定长度，否则默认长度为15
		len = len || 15;
		//循环生成字符串
		for (var i = 0, index; i < len; i++) {
			index = (function(randomIndexFunc, i) {
				return randomIndexFunc(min, max, i, randomIndexFunc);
			})(function(min, max, i, _self) {
				let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
					numStart = _charStr.length - 10;
				if (i == 0 && indexTemp >= numStart) {
					indexTemp = _self(min, max, i, _self);
				}
				return indexTemp;
			}, i);
			_str += _charStr[index];
		}
		return _str;
	},

	/**
	 * 返回上一页
	 */
	back: (delta = 1) => {
		let pages = getCurrentPages(); //当前页
		// console.log("pages", pages);
		// console.log("(pages[pages.length - 1].$page.fullPath", pages[pages.length - 1].$page.fullPath);
		if (pages.length == 1) {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		} else {
			uni.navigateBack({
				delta: delta
			});
		}
	},

	/**
	 * 获取分页组件配置参数
	 * @param {Object} config
	 */
	getUpOption: (config) => {
		let data = {
			use: true, // 是否启用上拉加载; 默认true
			auto: true, // 是否在初始化完毕之后自动执行上拉加载的回调; 默认true
			isLock: false, // 是否锁定上拉加载,默认false;
			isBoth: true, // 上拉加载时,如果滑动到列表顶部是否可以同时触发下拉刷新;默认true,两者可同时触发;
			page: {
				num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
				size: 10, // 每页数据的数量
				time: null // 加载第一页数据服务器返回的时间; 防止用户翻页时,后台新增了数据从而导致下一页数据重复;
			},
			noMoreSize: 10, // 如果列表已无数据,可设置列表的总数量要大于等于5条才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
			offset: 80, // 距底部多远时,触发upCallback(仅mescroll-uni生效, 对于mescroll-body则需在pages.json设置"onReachBottomDistance")
			bgColor: 'transparent', // 背景颜色 (建议在pages.json中再设置一下backgroundColorTop)
			textColor: 'gray', // 文本颜色 (当bgColor配置了颜色,而textColor未配置时,则textColor会默认为白色)
			textLoading: '加载中 ...', // 加载中的提示文本
			textNoMore: '-- 暂无更多卡劵信息 --', // 没有更多数据的提示文本
			toTop: {
				// 回到顶部按钮,需配置src才显示
				src: 'https://www.mescroll.com/img/mescroll-totop.png', // 图片路径
				offset: 1000, // 列表滚动多少距离才显示回到顶部按钮,默认1000
				duration: 300, // 回到顶部的动画时长,默认300ms (当值为0或300则使用系统自带回到顶部,更流畅; 其他值则通过step模拟,部分机型可能不够流畅,所以非特殊情况不建议修改此项)
				zIndex: 9990, // fixed定位z-index值
				left: null, // 到左边的距离, 默认null. 此项有值时,right不生效. (支持20, "20rpx", "20px", "20%"格式的值, 其中纯数字则默认单位rpx)
				right: 20, // 到右边的距离, 默认20 (支持20, "20rpx", "20px", "20%"格式的值, 其中纯数字则默认单位rpx)
				bottom: 250, // 到底部的距离, 默认120 (支持20, "20rpx", "20px", "20%"格式的值, 其中纯数字则默认单位rpx)
				safearea: false, // bottom的偏移量是否加上底部安全区的距离, 默认false, 需要适配iPhoneX时使用 (具体的界面如果不配置此项,则取mescroll组件props的safearea值)
				width: 72, // 回到顶部图标的宽度, 默认72 (支持20, "20rpx", "20px", "20%"格式的值, 其中纯数字则默认单位rpx)
				radius: '50%' // 圆角, 默认"50%" (支持20, "20rpx", "20px", "20%"格式的值, 其中纯数字则默认单位rpx)
			},
			empty: {
				use: true, // 是否显示空布局
				icon: 'https://chaobusi.oss-cn-hangzhou.aliyuncs.com/other/empty.png', // 图标路径
				tip: '暂无更多卡劵信息', // 提示
				fixed: false, // 是否使用fixed定位,默认false; 配置fixed为true,以下的top和zIndex才生效 (transform会使fixed失效,最终会降级为absolute)
				top: '100rpx', // fixed定位的top值 (完整的单位值,如 "10%"; "100rpx")
				zIndex: 99 // fixed定位z-index值
			},
			onScroll: true // 是否监听滚动事件, 默认false, 仅mescroll-uni生效; mescroll-body直接声明onPageScroll (配置为true时,可@scroll="scroll"获取到滚动条位置和方向; 注意监听列表滚动是非常耗性能的,很容易出现卡顿,非特殊情况不要配置此项)
		};

		return api.assiginObj(data, config);
	},

	assiginObj: (target = {}, sources = {}) => {
		let obj = target;
		if (typeof target != 'object' || typeof sources != 'object') {
			return sources; // 如果其中一个不是对象 就返回sources
		}
		for (let key in sources) {
			// 如果target也存在 那就再次合并
			if (target.hasOwnProperty(key)) {
				obj[key] = api.assiginObj(target[key], sources[key]);
			} else {
				// 不存在就直接添加
				obj[key] = sources[key];
			}
		}
		return obj;
	},

	/**
	 * 数字》10000  显示 几万
	 * @param {number} num  数字
	 * @param {number} fixedNum 
	 * @returns 
	 */
	exchangeUnit: (num,fixedNum = 1) => {
    num = Number(num)
    if (num >= 10000) {
      var digit = num / 10000
      var count = digit.toFixed(6).slice(0, -(6-fixedNum))
      count = Math.max(count)
      return count + 'w'
    } else {
      return num
    }
  },

	/**
	 * 返回某个数字的美金形式  有兼容性问题  app端报错  小程序端ok
	 * @param {number} number 
	 * @returns {number} 
	 */
  formatDollar: (number) => {
		let res = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number);
		res = res.replace('$', '');
		console.log('reeee',res)
		return res.split('.')[0]
	},

	/**
	 * 返回某个数字的美金形式
	 * @param {number} num 
	 * @param {number} decimal  保留小数的位数
	 * @returns 
	 */
	formatToUSD: (num,decimal = 0) => {
		// 将数字转换为字符串，并保留两位小数
		const numStr = (num / 1).toFixed(decimal);

		// 使用正则表达式替换每三位数字前加上逗号
		const parts = numStr.split('.');
		parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');

		// 返回格式化的字符串
		return parts.join('.');
	},

	/**
	 * 将某个日期转换成 几秒前  几天前  几周前
	 * @param {Number} dateTimeStamp  要转换的时间戳
	 * @returns 
	 */
	timeText: (dateTimeStamp) => {
		// return moment(time).fromNow();
		let newTime = api.getDateTimeStamp(dateTimeStamp)
		let minute = 1000 * 60;
		let hour = minute * 60;
		let day = hour * 24;
		let halfamonth = day * 15;
		let month = day * 30;
		let now = new Date().getTime();

		//如果是去年发的  就显示 XXXX-XX-XX 时间
		const currentYear = new Date().getFullYear();
		const timeYear = new Date(newTime).getFullYear();
		if(timeYear < currentYear) return moment(newTime).format('YYYY-MM-DD')

		let diffValue = now - newTime;
		if(diffValue <= 0){return '刚刚';}
		let monthC = diffValue/month;
		let weekC = diffValue/(7*day);
		let dayC = diffValue/day;
		let hourC = diffValue/hour;
		let minC = diffValue/minute;
		let result = '';
		if(monthC>=1){
			result="" + parseInt(monthC) + "月前";
		}
		else if(weekC>=1){
			result="" + parseInt(weekC) + "周前";
		}
		else if(dayC>=1){
			result="" + parseInt(dayC) +"天前";
		}
		else if(hourC>=1){
			result="" + parseInt(hourC) +"小时前";
		}
		else if(minC>=1){
			result="" + parseInt(minC) +"分钟前";
		}else{
			result="刚刚";
		}
		
		return result;
	},
	/**
	 * 转换标准时间为时间戳
	 * @param {Number} dateStr 
	 * @returns 
	 */
	getDateTimeStamp(dateStr){
		return Date.parse(dateStr.replace(/-/gi,"/"));
	},

	/**
	 * 处理时间  如果是去年就显示年月日  如果是今天 就显示月日
	 * @param {Number} dateStr 
	 * @returns 
	 */
	timeText2:(dateTimeStamp) => {
		let newTime = api.getDateTimeStamp(dateTimeStamp)
		const currentYear = new Date().getFullYear();
		const timeYear = new Date(newTime).getFullYear();
		if(timeYear < currentYear) {
			return moment(newTime).format('YYYY-MM-DD')
		}else{
			return moment(newTime).format('MM-DD')
		}
	},

}
export default api;
